package com.weilx959.spt.app.controller;

import com.jfoenix.controls.JFXTextArea;
import com.weilx959.spt.app.context.LogThreadContext;
import com.weilx959.spt.core.interfaces.Controller;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class LogViewController implements Controller {
    @FXML
    private AnchorPane rootPane;

    @FXML
    private JFXTextArea logTextArea;

    @FXML
    private void initialize() {
        // load log file and show it in logTextArea
        LogThreadContext.start(e-> {
            log.error("Error in LogView: ", e);
        }, logs -> {
            logTextArea.appendText(StringUtils.defaultString(logs, StringUtils.EMPTY));
            logTextArea.appendText("\n");
        });
    }

    @Override
    public Pane getRootPane() {
        return rootPane;
    }

    @Override
    public boolean onDestroy() {
        // stop log file monitoring
        LogThreadContext.stop();
        return true;
    }

    public void scrollToTop(ActionEvent event) {
        event.consume();
        logTextArea.setScrollTop(0);
    }

    public void scrollToBottom(ActionEvent event) {
        event.consume();
        logTextArea.setScrollTop(Double.MAX_VALUE);
    }

    public void toggleWrap(ActionEvent event) {
        event.consume();
        logTextArea.setWrapText(!logTextArea.isWrapText());
    }

    public void clearLog(ActionEvent event) {
        event.consume();
        logTextArea.clear();
    }
}
